package com.peza.mines.logic;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import com.peza.mines.domain.Board;
import com.peza.mines.domain.Field;
import com.peza.mines.domain.FieldClass;

public class LogicImpl implements Logic{

	private Logger logger = Logger.getLogger(this.getClass());
	
	private Board board;
	
	private Set <Field> checked = new HashSet<Field>();
	
	public LogicImpl(Board board){
		this.board = board;
	}
	
	
	
	public void openWater(Field center){
		logger.debug("CENTER field:" + center);
		int x = center.getxPos();
		int y = center.getYpos();
		
		if (!center.isMine()){
			
			center.setVisible(true);
			board.updateField(center);
			
			if (center.getProx() == 0){
				for (int posy = -1; posy < 2; posy++){
					for (int posx = -1; posx < 2; posx++ ){
						if (!(posx == x && posy == y)){
							try {
								Field satellite = board.getField(y + posy, x + posx);
								if (!satellite.isVisible()){
									openWater(satellite);
								} 
								
							} catch (ArrayIndexOutOfBoundsException e) {
								//System.out.println(".");
								// do nothing
							} catch (StackOverflowError e){
								logger.error("Stack overflow");
							}
						}
					}
				}
			}	
		} 		
	}

		
	
	public Board click(Field field) {
		
		if (field.isMine()){
			board.setExploded(true);
			return board;
		} else {	
			checked.clear();
			field.setVisible(true);
			board.updateField(field);
			openWater(field);
			return board;
		}
	}

}
